package com.example.esaclient;

import java.io.File;
import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.URL;
import java.util.HashMap;
import java.util.UUID;

import android.graphics.Picture;
import android.os.Environment;
import android.util.Log;

public class EsaTag{

	public String tagger,taggerPicture,message,time,socialNetwork,picture;
	public HashMap<String,Object> feed;
	public String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/ESAClient/";
	private String localPath="";
	
	public EsaTag(){
		message=tagger=socialNetwork=taggerPicture=time=picture="";
	}
	
	
	public EsaTag(String esaMsg){
		String[] s;
		s=esaMsg.split("\\+\\-\\+");
		feed=new HashMap<String, Object>();
		if(s.length>=5){
			tagger=s[0];
			taggerPicture=s[1];
			message=s[2];
			time=s[3];
			socialNetwork=s[4];		
		if(s.length>5)
			picture=s[5];
		
		feed.put("message", message);
		feed.put("time", time);
		feed.put("socialNetwork","Via "+ socialNetwork);

			if (!taggerPicture.equals("")) {

			
				localPath = loadImageFromWebOperations(taggerPicture, path);
			
				feed.put("taggerPicture", localPath);
			} else
				feed.put("taggerPicture", "");
		
		feed.put("tagger",tagger);
		
		if(picture!="")
			feed.put("picture",  loadImageFromWebOperations(picture, path));
		}
		else{
		message="There are no Tags.";
		feed.put("message", message);
		feed.put("time", "");
		feed.put("socialNetwork","");
		feed.put("taggerPicture", "");
		feed.put("tagger","");
		
		}
		
	}
	
	public static String loadImageFromWebOperations(String url, String path) {

		File folder = new File(path);
		boolean success = true;
		if (!folder.exists()) {
			success = folder.mkdir();
		}
		if (success) {
			try {
				String s[] = url.split("/");
				String filename = s[s.length - 1];

				File dir = new File(path);

				/*int dotPosition = filename.lastIndexOf(".");
				
				if (dotPosition !=3 ) 
					filename=UUID.randomUUID().toString();
				    */
				if(filename.equals("picture"))
					filename=UUID.randomUUID().toString();
				
				
				File f = new File(dir + "/" + filename);

				if (!f.exists()) {
					Log.w("ESA", "Downloading image: " + url);
					InputStream is = (InputStream) new URL(url).getContent();

					f.createNewFile();
					FileOutputStream fos = new FileOutputStream(f);
					try {

						byte[] b = new byte[100];
						int l = 0;
						while ((l = is.read(b)) != -1)
							fos.write(b, 0, l);

						fos.close();

					} catch (Exception e) {
						return "";
					}
					Log.w("ESA", "Downloaded to " + f.getAbsolutePath());
				}
				return f.getAbsolutePath();
			} catch (Exception e) {
				System.out.println("Exc=" + e);
				return "";

			}
		} else {
			Log.e("ESA", "Failed to create directory " + path);
			return "";
		}

	}
	
}
